define(function(require, exports, module) {
    'use strict';
    
    var rk = require('rk');
    
    
    require('./groupSetCtrl');

    $.widget('rk.privateMsgDetailCtrl', {
        options: {
            privateMsgId: null,
            pageNo: 1,
            pageSize: 20,
            isGroup: 0,
            groupDead: 0
        },
        _create: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;
        },
        _detailLoading: false,
        _detailLastHeight: 0,
        _init: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            try {
                me.destroy();
            } catch (e) {}

            var newMsgTpl = require('page/tmpl/privatemsg/privateMsgDetail.tpl');
            var newMsgHtml = rk.templateText(newMsgTpl);

            elem.append(newMsgHtml);
            if(Number(opt.isGroup) == 1 && Number(opt.groupDead) == 1){
                elem.find('.set').remove();
            }

            elem.find("div.pm-messagebox-body").beScroll({
                whileScrolling: function() {
                    if (elem.find('.mCSB_dragger').css('top') === "0px" && !me._detailLoading) {
                        opt.pageNo++;
                        me._detailLoading = true;
                        me._compositeData(elem, false, function(dialogue) {
                            elem.find("div.pm-messagebox-body").beScrollTo(elem.find("div.pm-messagebox-body").find('.mCSB_container').height() - me._detailLastHeight);
                        }, function() {
                            me._detailLoading = false;
                            me._detailLastHeight = elem.find("div.pm-messagebox-body").find('.mCSB_container').height();
                        });
                    }
                }
            });

            me.pmTitle = elem.find("div.pm-messagebox-header");
            me.pmDialogue = elem.find("div.pm-messagebox-body").find('.mCSB_container');
            me.pmReply = elem.find("div.pm-messagebox-footer");
            var pmTitle = me.pmTitle,
                pmDialogue = me.pmDialogue,
                pmReply = me.pmReply;

            me._clearData();
            me._bindEvents();
            //pmDialogue.scrollLoader("lock");
            me._detailLoading = true;
            me._compositeData(elem, true, function() {
                setTimeout(function() {
                    elem.find("div.pm-messagebox-body").beScrollTo('bottom');
                }, 100);
            }, function() {
                //pmDialogue.scrollLoader("release");
                me._detailLoading = false;
                me._detailLastHeight = elem.find("div.pm-messagebox-body").find('.mCSB_container').height();
            });
            pmReply.trigger("init");

            //绑定当前私信的id
            elem.data("privateMsgBindId", opt.privateMsgId);
            elem.show();
        },
        destroy: function() {
            var me = this;
            var elem = me.element;

            try {
                $('.pg-pm-gset').groupSetCtrl('destroy');
            } catch (e) {
                $('.pg-pm-gset').empty();
                $('.pg-pm-gset').hide();
            }

            elem.empty();
            elem.hide();
            me._clearData();
            /*me.picUploadBtn.uploadify("destroy");
            me.fileUploadBtn.uploadify("destroy");
            $.Widget.prototype.destroy.apply(me);*/
        },
        closeDetail: function() {
            var me = this;
            var elem = me.element;

            elem.hide();
        },
        showDetail: function() {
            var me = this;
            var elem = me.element;

            elem.show();
        },
        currentId: function() {
            var me = this;
            var elem = me.element;
            return elem.data("privateMsgBindId");
        },
        _bindEvents: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            me._bindTitleEvents();
            me._bindDialogueEvents();
            me._bindReplyEvents();
        },
        _clearData: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var pmTitle = me.pmTitle,
                pmDialogue = me.pmDialogue,
                pmReply = me.pmReply;
            pmTitle.trigger("clearData");
            pmDialogue.trigger("clearData");
            //清除绑定id
            elem.removeData("privateMsgBindId");
        },
        memberIdList: null,
        users: null,
        groupName: null,
        _bindTitleEvents: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var pmTitle = me.pmTitle,
                pmDialogue = me.pmDialogue,
                pmReply = me.pmReply;
            //title
            //close btn
            elem.find('.close').click(function() {
                me.destroy();
            });

            elem.find('.set').click(function() {
                me.destroy();
                $('.pg-pm-gset').groupSetCtrl({
                    privateMsgId: opt.privateMsgId,
                    memberIdList: me.memberIdList,
                    users: me.users,
                    groupName: me.groupName,
                    pmType: opt.isGroup
                });
            });
            //load title data
            pmTitle.on("loadData", function(evt, data) {
                var target = $(this);

                me.memberIdList = data.memberIdList;
                me.users = data.users;
                me.groupName = data.pmTitle;
                target.find("div.name").html('<a href="javascript:;">' + data.pmTitle + '</a>');
            });
            pmTitle.on("clearData", function(evt) {
                var pT = $(this);
                pT.find("div.name").empty();
            });
        },
        _bindDialogueEvents: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var pmTitle = me.pmTitle,
                pmDialogue = me.pmDialogue,
                pmReply = me.pmReply;

            var latestShowTime = 0,
                oldestShowTime = 0,
                SPLIT_MILL_TIME = 180000;
            //用来处理详细中的时间片段，一个存储最新的时间，一个存储最老的时间
            //dialogue
            pmDialogue.on("loadData", function(evt, data, firstTime, isAppend) {
                var container = $(this);

                var _detail_base = function(o) {
                    var cuser = data.users[o.createdBy];
                    cuser.icon = cuser.icon || DEFAULTS.USER_DEFAULT_ICON;

                    var username = '';
                    if (o.createdBy !== window.SESSION.user.id) {
                        username = data.users[o.createdBy].name;
                    }

                    var detailTpl = require('page/tmpl/privatemsg/snsPrivateMsgDetail.tpl');
                    var detailData = {
                        createdUser: cuser,
                        username: username,
                        isGroup: opt.isGroup,
                        fromClass: (o.createdBy == window.SESSION.user.id ? "right" : "left"),

                    };
                    var detailHtml = rk.templateText(detailTpl, detailData);

                    return $(detailHtml);
                }

                var _detail_content = function(o) {
                    var messageTpl = require('page/tmpl/privatemsg/snsPrivateMsgSnipMessage.tpl');

                    var reply = '';
                    var username = '';
                    if (o.createdBy !== window.SESSION.user.id) {
                        username = data.users[o.createdBy].name;
                        reply = '<a href="javascript:;" title="回复" class="reply" replyto="' + username + '"></a>';
                    } else {
                        username = "";
                    }

                    //var txt_message = me._unescapeEntity(me._emoji(o.content));
                    var txt_message = me._emoji(o.content);
                    var urlRegx = /(http:\/\/|https:\/\/)((\w|=|\?|\.|\/|&|-)+)/g;
                    txt_message = txt_message.replace(urlRegx, '<a href="$1$2" target="_blank">$1$2</a>').replace(/\n/g, "<br />");

                    var messageData = {
                        replyView: reply,
                        username: username,
                        content: txt_message,
                        fromClass: (o.createdBy == window.SESSION.user.id ? "right" : "left")
                    };
                    var messageHtml = rk.templateText(messageTpl, messageData);
                    return $(messageHtml);
                }

                var _detail_img = function(o) {
                    var imgHtml = "";
                    if(o.file) {
                        var imgData = {
                            url: o.file.spicurl,
                            lurl: o.file.lpicurl,
                            ourl: o.file.fileurl
                        };

                        var imgTpl = require('page/tmpl/privatemsg/snsPrivateMsgSnipImg.tpl');
                        imgHtml = rk.templateText(imgTpl, imgData);
                    }else{
                        imgHtml = '<div class="detail_attachment">图片无法正常显示</div>';
                    }

                    return $(imgHtml);
                }

                var _detail_file = function(o) {
                    var PREIVIEWING = "/static/img/file_previewing.png",
                        NO_PREVIEW = "/static/img/file_nopreview.jpg",
                        PREVIEW_FAIL = "/static/img/preview_fail.png";

                    var fileTpl = require('page/tmpl/privatemsg/snsPrivateMsgSnipFile.tpl');

                    var imgurl = '';
                    if (o.file.type === 0) {
                        if (o.file.swfurl == "") {
                            imgurl = PREIVIEWING;
                        } else {
                            imgurl = o.file.imgurl;
                        }
                    } else {
                        if (o.file.swfurl == "CONVERT_FAILED") {
                            imgurl = PREVIEW_FAIL;
                        } else {
                            imgurl = NO_PREVIEW;
                        }
                    }

                    var fileData = {
                        fileid: o.file.id,
                        imgurl: imgurl,
                        systemId: 506, //私信的system id
                        itemId: o.id,
                        filename: o.file.filename,
                        tfcode: o.file.tfcode
                    };

                    var fileHtml = rk.templateText(fileTpl, fileData);

                    return $(fileHtml);
                }

                var _detail_sound = function(o) {
                    var LEFT_PNG = "/static/img/v3.0/pm_sound_right.png",
                        RIGHT_PNG = "/static/img/v3.0/pm_sound_left.png";

                    var soundTpl = require('page/tmpl/privatemsg/snsPrivateMsgSnipSound.tpl');

                    var reply = '';
                    var isself = 0;
                    var imgurl = '';
                    if (o.createdBy !== window.SESSION.user.id) {
                        reply = '<a href="javascript:;" title="回复" class="reply" replyto="' + data.users[o.createdBy].name + '"></a>';
                        imgurl = RIGHT_PNG;
                    } else {
                        isself = 1;
                        imgurl = LEFT_PNG;
                    }

                    var soundData = {
                        pmId: o.id,
                        replyView: reply,
                        imgurl: imgurl,
                        isself: isself,
                        duration: o.sound.duration,
                        fromClass: (o.createdBy == window.SESSION.user.id ? "right" : "left")
                    };

                    var soundHtml = rk.templateText(soundTpl, soundData);

                    return $(soundHtml);
                }

                var _detail_notice = function(o) {
                    var noticeHtml = '<div class="message-notice"><span>' + o.content + '</span></div>';

                    return $(noticeHtml);
                }

                var _detail_notice_quit = function(o) {
                    var noticequitHtml = '<div class="message_notice">' + data.users[o.createdBy].name + o.content + '</div>';

                    return $(noticequitHtml);
                }

                var _switch_type = function(type, o, isAppend) {
                    var pendFun = isAppend ? "appendTo" : "prependTo";
                    switch (type) {
                        case 5:
                            //notice
                            _detail_notice(o).prependTo(container);
                            break;
                        case 6:
                            //notice
                            _detail_notice_quit(o).prependTo(container);
                            break;
                        case 7:
                            //notice
                            _detail_notice_quit(o).prependTo(container);
                            break;
                        case 0:
                            //最简单的message
                            var detail = _detail_base(o),
                                content = _detail_content(o);
                            content.appendTo(detail);
                            detail[pendFun](container);
                            break;
                        case 1:
                            //img
                            var detail = _detail_base(o),
                                content = _detail_content(o),
                                img = _detail_img(o);
                            img.appendTo(content.find("div.info_content"));
                            content.appendTo(detail);
                            detail[pendFun](container);
                            break;
                        case 2:
                            //file
                            var detail = _detail_base(o),
                                content = _detail_content(o);
                            _detail_file(o).appendTo(content.find("div.info_content"));
                            content.appendTo(detail);
                            detail[pendFun](container);
                            break;
                        case 3:
                            //sound
                            var detail = _detail_base(o),
                                sound = _detail_sound(o);
                            sound.appendTo(detail);
                            detail[pendFun](container);
                            break;
                    }
                }

                if (!isAppend) {
                    $.each(data.pmDetailList, function(i, o) {
                        var type = o.type;
                        if (i === 0 && firstTime) {
                            latestShowTime = o.createdAt;
                            oldestShowTime = o.createdAt;
                        }
                        if ((oldestShowTime - o.createdAt) > SPLIT_MILL_TIME) {
                            //多于SPLIT_MILL_TIME,则插入一条时间信息
                            var d = '<div class="time-line"><span>-----------</span><span class="data">' + me._parseDate(new Date(oldestShowTime)) + '</span><span>-----------</span></div>';
                            //插入时间
                            oldestShowTime = o.createdAt;
                            $(d).prependTo(container);
                        }
                        _switch_type(type, o, isAppend);
                        if (i == (data.pmDetailList.length - 1)) {
                            //最后一条
                            var d = '<div class="time-line"><span>-----------</span><span class="data">' + me._parseDate(new Date(o.createdAt)) + '</span><span>-----------</span></div>';
                            oldestShowTime = o.createdAt;
                            $(d).prependTo(container);
                        }
                    });
                } else {
                    $.each(data.pmDetailList, function(i, o) {
                        var type = o.type;
                        if ((o.createdAt - latestShowTime) > SPLIT_MILL_TIME) {
                            //多于SPLIT_MILL_TIME,则插入一条时间信息
                            var d = '<div class="time-line"><span>-----------</span><span class="data">' + me._parseDate(new Date(o.createdAt)) + '</span><span>-----------</span></div>';
                            //插入时间
                            latestShowTime = o.createdAt;
                            $(d).appendTo(container);
                        }
                        _switch_type(type, o, isAppend);
                    });
                }
                pmDialogue.find("div.detail_attachment img.nc_privatemsg_img_preview").trigger("previewImg");
                if (isAppend) {
                    setTimeout(function() {
                        elem.find("div.pm-messagebox-body").beScrollTo('bottom');
                    }, 50);
                }
            });
            pmDialogue.on("clearData", function(evt) {
                var target = $(this);
                target.find("div.pm-messagebox-body").empty();
            });

            //sound play
            pmDialogue.on("click", "div.nc-jplayer", function(evt) {
                var LEFT_PNG = "/static/img/v3.0/pm_sound_left.png",
                    RIGHT_PNG = "/static/img/v3.0/pm_sound_right.png",
                    LEFT_GIF = "/static/img/v3.0/voice_playing_left.gif",
                    RIGHT_GIF = "/static/img/v3.0/voice_playing_right.gif";
                var target = $(this);
                var pmid = target.attr("pmid"),
                    isself = target.attr("isself");

                //clear all sound
                elem.find('audio').each(function() {
                    var a_target = $(this);
                    if (a_target.parent().attr('pmid') !== pmid) {
                        try {
                            a_target[0].pause();
                            a_target[0].currentTime = 0;
                        } catch (e) {}
                    }
                });

                //configure target player
                var player = target.find('audio');
                if (player.attr('src') !== undefined) {
                    if (player[0].paused) {
                        player[0].play();
                    } else {
                        player[0].pause();
                        player[0].currentTime = 0;
                    }
                } else {
                    player.on("play", function() {
                        var img = target.find("img");
                        if (isself && isself == '1') {
                            img.attr("src", RIGHT_GIF);
                        } else {
                            img.attr("src", LEFT_GIF);
                        }
                    });
                    player.on("ended", function() {
                        var img = target.find("img");
                        if (isself && isself == '1') {
                            img.attr("src", RIGHT_PNG);
                        } else {
                            img.attr("src", LEFT_PNG);
                        }
                    });
                    player.on("pause", function() {
                        var img = target.find("img");
                        if (isself && isself == '1') {
                            img.attr("src", RIGHT_PNG);
                        } else {
                            img.attr("src", LEFT_PNG);
                        }
                    });

                    $.getJSON("/json/sns_wx/mp3.action", {
                        pmDetailId: pmid
                    }, function(res) {
                        if (res.data != "" && res.data.indexOf("mp3") > -1) {
                            player.attr('src', res.data);
                            player[0].play();
                        }
                    });
                }
            });

            pmDialogue.on("click", "a.reply", function(evt) {
                var target = $(this);
                var username = target.attr("replyto");
                if (username) {
                    var eContainer = pmReply.find("div.comment_publish"),
                        eTextarea = eContainer.find("div.comment_edit>textarea");
                    eTextarea.trigger("click").val('回复 ' + username + '，').caret(0, 9999);
                }
            });
            //图片预览
            pmDialogue.on("previewImg", "div.detail_attachment img.nc_privatemsg_img_preview", function(evt) {
                $(this).each(function(i) {
                    var target = $(this);
                    target.lightBox({
                        imagesData: [{
                            s_url: target.attr("src"),
                            l_url: target.attr("lurl"),
                            url: target.attr("ourl")
                        }]
                    });
                });
            });
            //文档预览
            pmDialogue.on("click", "div.detail_attachment img.nc_privatemsg_file_preview", function(evt) {
                var target = $(this);
                evt.preventDefault();
                var systemId = target.attr("systemid"),
                    itemId = target.attr("itemid");
                var url = '/json/sns_preview/commonFile.action?systemId=' + systemId + '&systemItemId=' + itemId;
                var previewHtml;
                $.getJSON(url).done(function(json) {
                    if (json.status === 100000) {
                        return;
                    }
                    var pre = '<div class="pop_up_02"><div class="pop_up_content"><div class="pop_up_inner" autofocus="true">';
                    var end = '</div></div></div>';
                    var content;
                    if (json.status === 210001) {
                        content = rk.i18n('PRIVATEMSG_ORIGINAL_CONTENT_IS_DELETE');
                    }
                    if (json.status === 0) {
                        content = '<div class="document_view"></div>';
                    }
                    if (!previewHtml) {
                        previewHtml = [pre, content, end].join('');
                    }
                    $(previewHtml).popup({
                        width: 700,
                        height: 600,
                        title: rk.i18n('PRIVATEMSG_FILE_PREVIEW'),
                        resizable: true,
                        actions: {},
                        create: function() {
                            new FlexPaperViewer('/static/swf/flexpager.swf', $(this).find('div.document_view').uniqueId().attr('id'), {
                                config: {
                                    SwfFile: json.data.previewUrl,
                                    Scale: 0.6,
                                    ZoomTransition: "easeOut",
                                    ZoomTime: 0.5,
                                    ZoomInterval: 0.1,
                                    FitPageOnLoad: false,
                                    FitWidthOnLoad: true,
                                    PrintEnabled: true,
                                    FullScreenAsMaxWindow: false,
                                    ProgressiveLoading: true,
                                    PrintToolsVisible: true,
                                    ViewModeToolsVisible: true,
                                    ZoomToolsVisible: true,
                                    FullScreenVisible: true,
                                    NavToolsVisible: true,
                                    CursorToolsVisible: true,
                                    SearchToolsVisible: true,
                                    localeChain: "zh_CN"
                                }
                            });
                        }
                    });
                }).fail(function(def, code, message) {
                    $.alert([code, message].join(':'));
                });
            });
        },
        _bindReplyEvents: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var pmTitle = me.pmTitle,
                pmDialogue = me.pmDialogue,
                pmReply = me.pmReply;

            var eContainer = pmReply.find("div.pm_sent"),
                eTextarea = eContainer.find("li.message_sent_li>textarea"),
                eAttach = eContainer.find("div.attachment"),
                eSubBtn = eContainer.find("a.pg-btn-blue");
            pmReply.on("init", function(evt) {
                var target = $(this);
                var HAS_INIT_FLAG = "hasInited";
                if (target.data(HAS_INIT_FLAG)) {
                    //maybe some operation
                    return;
                } else {
                    var btnIsEnabled = function(btn) {
                            return !btn.hasClass("disabled");
                        },
                        btnEnable = function(btn) {
                            btn.removeClass("disabled");
                        },
                        btnDisable = function(btn) {
                            if (!btn.hasClass("disabled")) {
                                btn.addClass("disabled");
                            }
                        };
                    var filequeue = $("#pm_new_filequeue");
                    var picUploadBtn = me.picUploadBtn = pmReply.find("div.pic_attachment");
                    var fileUploadBtn = me.fileUploadBtn = pmReply.find("div.file_attachment");
                    //设置一个id，是uploadify必须的
                    me.picUploadBtn.attr("id", "pm_pic_attachment_" + opt.privateMsgId);
                    me.fileUploadBtn.attr("id", "pm_file_attachment_" + opt.privateMsgId);

                    var modifyMessageBoxHeight = function() {
                        var pH = elem.css('height').slice(0, -2);
                        var delta_pH = pH - 479;
                        var bH = elem.find("div.pm-messagebox-body").css('height').slice(0, -2);
                        var new_bH = bH - delta_pH;

                        elem.find("div.pm-messagebox-body").css('height', new_bH);

                        if (eTextarea.css('height').slice(0, -2) > 49) {
                            eTextarea.css('overflow-y', 'scroll');
                        } else {
                            eTextarea.css('overflow-y', 'hidden');
                        }
                    }

                    eTextarea.autoTextarea({
                        maxHeight: 75,
                        minHeight: 49
                    }).bind("input propertychange", function() {
                        if ($(this).val().length > 0) {
                            btnEnable(eSubBtn);
                        } else {
                            if (!pmReply.data('uploadFile')) {
                                btnDisable(eSubBtn);
                            }
                        }
                    }).on("keydown", function(evt) {
                        if (evt.keyCode === 13 && !evt.ctrlKey && !evt.shiftKey && !evt.altKey) {
                            evt.preventDefault();
                            eSubBtn.trigger('click');
                        }
                        if (evt.keyCode === 13 && (evt.ctrlKey || evt.shiftKey || evt.altKey)) {
                            eTextarea.val($.trim(eTextarea.val()) + "\r\n");
                        }
                    }).bind("paste cut keydown keyup focus blur", function() {
                        modifyMessageBoxHeight();
                    });
                    eSubBtn.on("click", function(evt) {
                        evt.preventDefault();
                        if (btnIsEnabled(eSubBtn)) {
                            var cval = $.trim(eTextarea.val());
                            if (cval.length === 0 && !pmReply.data('uploadFile')) {
                                eTextarea.val("");
                                return false;
                            }
                            btnDisable(eSubBtn);
                            eSubBtn.text(rk.i18n('PRIVATEMSG_SENDING') + "...");
                            eTextarea.val("");
                            if (cval.length > 1000) {
                                btnEnable(eSubBtn);
                                eSubBtn.text(rk.i18n('PRIVATEMSG_SEND_OUT'));
                                rk.noticeError(rk.i18n('PRIVATEMSG_CONTENT_MAX_ERROR'));
                                return false;
                            }

                            var resetReplyElem = function(uploadFile) {
                                eTextarea.val("");
                                if (uploadFile) {
                                    if (uploadFile.fileType == 1) {
                                        picUploadBtn.uploadify("cancel", uploadFile.id);
                                    }
                                    if (uploadFile.fileType == 0) {
                                        fileUploadBtn.uploadify("cancel", uploadFile.id);
                                    }
                                }
                                filequeue.hide();
                                btnDisable(eSubBtn);
                                modifyMessageBoxHeight();
                            }

                            var params = {
                                privateMsgId: opt.privateMsgId,
                                content: cval
                            };
                            var uploadFile = pmReply.data('uploadFile');
                            if (uploadFile) {
                                var pmtype = 1;
                                if (uploadFile.fileType == 0) {
                                    pmtype = 2;
                                }
                                params = $.extend({}, params, {
                                    uploadFileName: uploadFile.name,
                                    pmType: pmtype,
                                    uploadFileUrl: uploadFile.fileUrl,
                                    uploadFileLength: uploadFile.fileLength,
                                    uploadFilePixels: uploadFile.filePixels
                                });
                            }
                            $.postJson("/json/sns_privatemsg/add-detail.action", params).done(function(json) {
                                if (json.status) {
                                    if(json.status == 230001){
                                        rk.noticeError('您已被移出讨论组');
                                    }else{
                                        rk.noticeError(json.status);
                                    }
                                    btnEnable(eSubBtn);
                                    eSubBtn.text(rk.i18n('PRIVATEMSG_SEND_OUT'));
                                    return;
                                }
                                if (json.data) {
                                    pmDialogue.trigger("loadData", [json.data, false, true]);
                                    resetReplyElem(uploadFile);
                                    setTimeout(function() {
                                        var scrollTop = pmDialogue[0].scrollHeight;
                                        pmDialogue.scrollTop(scrollTop);
                                    }, 50);
                                    $('#privatemsg').privateMsgCtrl("reorderList", json.data.pmId);
                                    btnDisable(eSubBtn);
                                } else {
                                    btnEnable(eSubBtn);
                                }
                                eSubBtn.text(rk.i18n('PRIVATEMSG_SEND_OUT'));
                            }).fail(function(def, code, message) {
                                eSubBtn.text(rk.i18n('PRIVATEMSG_SEND_OUT'));
                                btnEnable(eSubBtn);
                            });
                            //_hmt.push(['_trackEvent', 'privatemsg', 'send_message', window.SESSION.tenantName]);
                        }
                    });
                    //uploads
                    picUploadBtn.uploadify({
                        swf: '/swf/uploadify.swf',
                        uploader: '/json/global_uploadify/img-upload.action',
                        auto: true,
                        buttonClass: 'pic_attachment',
                        buttonCursor: 'hand',
                        buttonImage: '',
                        buttonText: rk.i18n('PRIVATEMSG_PICTURE'),
                        fileObjName: 'uploadFile',
                        fileSizeLimit: '5MB',
                        fileTypeDesc: rk.i18n('PRIVATEMSG_PICTURE'),
                        fileTypeExts: '*.jpg;*.gif;*.png;*.JPEG;*.BMP',
                        removeCompleted: false,
                        successTimeout: 30,
                        multi: false,
                        queueID: "pm_new_filequeue",
                        width: "auto",
                        height: "auto",
                        itemTemplate: '<div class="upload_popup" id="${fileID}"><div class="uploadifyQueue" style="display: block;"><div class="uploadifyQueueItem completed clear"><span class="fileName">${fileName} (${fileSize})</span><span class="data"></span></div><div class="uploadify-progress"><p class="nc_upload_processing">' + rk.i18n('PRIVATEMSG_UPLOADING') + '</p></div></div><a fileID="${fileID}" href="javascript:;" class="close" title="' + rk.i18n('PRIVATEMSG_CLOSE') + '"></a></div>',
                        onSelect: function(file) {
                            var d = pmReply.data('uploadFile');
                            if (d) {
                                picUploadBtn.uploadify("cancel", d.id);
                                $("#" + d.id).remove();
                            }
                        },
                        onCancel: function(file) {
                            pmReply.removeData('uploadFile');
                            if ($.trim(eTextarea.val()) < 1) {
                                btnDisable(eSubBtn);
                            }
                        },
                        onUploadStart: function(file) {
                            picUploadBtn.uploadify('settings', 'formData', {
                                'pageTenantId': SESSION.tenantId,
                                'uploadFileName': file.name,
                                'uploadContentType': file.type.slice(1)
                            });
                            filequeue.show();
                            filequeue.find(".nc_upload_processing").show();
                            filequeue.find("div.show_attachment").hide();
                            //
                        },
                        onUploadSuccess: function(file, data, response) {
                            data = $.parseJSON(data);
                            if (data.status == 0) {
                                pmReply.data('uploadFile', $.extend(data.data.returnParams, {
                                    fileType: 1
                                }, file));
                                filequeue.find(".nc_upload_processing").hide();
                                filequeue.find("div.show_attachment").show();
                                btnEnable(eSubBtn);

                                filequeue.find('a.close').on('click', function() {
                                    var target = $(this);
                                    picUploadBtn.uploadify('cancel', target.attr('fileID'));
                                });
                            } else {
                                rk.noticeError(rk.i18n('PRIVATEMSG_UPLOAD_ERROR'));
                                picUploadBtn.uploadify("cancel", file.id);
                            }
                        },
                        onDialogClose: function(queueData) {
                            queueData.files = {};
                            queueData.uploadQueue.splice(0, queueData.uploadQueue.length);
                        }
                    });
                    fileUploadBtn.uploadify({
                        swf: '/swf/uploadify.swf',
                        uploader: '/json/global_uploadify/files-upload.action',
                        auto: true,
                        buttonClass: 'file_attachment',
                        buttonCursor: 'hand',
                        buttonImage: '',
                        buttonText: rk.i18n('PRIVATEMSG_FILE'),
                        fileObjName: 'uploadFile',
                        fileSizeLimit: '80MB',
                        fileTypeDesc: rk.i18n('PRIVATEMSG_FILE'),
                        fileTypeExts: '',
                        removeCompleted: false,
                        successTimeout: 30,
                        multi: false,
                        queueID: "pm_new_filequeue",
                        width: "auto",
                        height: "auto",
                        itemTemplate: '<div class="upload_popup" id="${fileID}"><div class="uploadifyQueue" style="display: block;"><div class="uploadifyQueueItem completed clear"><span class="fileName">${fileName} (${fileSize})</span><span class="data"></span></div><div class="uploadify-progress"><p class="nc_upload_processing">' + rk.i18n('PRIVATEMSG_UPLOADING') + '</p></div></div><a fileId="${fileID}" href="javascript:;" class="close" title="' + rk.i18n('PRIVATEMSG_CLOSE') + '"></a></div>',
                        onSelect: function(file) {
                            var d = pmReply.data('uploadFile');
                            if (d) {
                                fileUploadBtn.uploadify("cancel", d.id);
                                $("#" + d.id).remove();
                            }
                        },
                        onCancel: function(file) {
                            pmReply.removeData('uploadFile');
                            if ($.trim(eTextarea.val()) < 1) {
                                btnDisable(eSubBtn);
                            }
                        },
                        onUploadStart: function(file) {
                            pmReply.data("uploadFileId", (file.id));
                            fileUploadBtn.uploadify('settings', 'formData', {
                                'pageTenantId': SESSION.tenantId,
                                'uploadFileName': file.name,
                                'uploadContentType': file.type.slice(1)
                            });
                            filequeue.show();
                            filequeue.find(".nc_upload_processing").show();
                            filequeue.find("div.show_attachment").hide();
                        },
                        onUploadSuccess: function(file, data, response) {
                            data = $.parseJSON(data);
                            if (data.status == 0) {
                                pmReply.data('uploadFile', $.extend(data.data.returnParams, {
                                    fileType: 0
                                }, file));
                                filequeue.find(".nc_upload_processing").hide();
                                filequeue.find("div.show_attachment").show();
                                btnEnable(eSubBtn);

                                filequeue.find('a.close').on('click', function() {
                                    var target = $(this);
                                    fileUploadBtn.uploadify('cancel', target.attr('fileID'));
                                });
                            } else {
                                rk.noticeError(rk.i18n('PRIVATEMSG_UPLOAD_ERROR'));
                                fileUploadBtn.uploadify("cancel", file.id);
                            }
                        },
                        onDialogClose: function(queueData) {
                            queueData.files = {};
                            queueData.uploadQueue.splice(0, queueData.uploadQueue.length);
                        }
                    });
                    target.data(HAS_INIT_FLAG, true);
                }
            });
        },
        _compositeData: function($container, firstTime, scrollFunction, hasMoreFunction) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var pmTitle = me.pmTitle,
                pmDialogue = me.pmDialogue,
                pmReply = me.pmReply;

            //$.getJSON("/json/sns_privatemsg/detail.action", {
            $.getJSON('/json/sns_wx/detail.action', {
                privateMsgId: opt.privateMsgId,
                pageNo: opt.pageNo,
                pageSize: opt.pageSize
            }).done(function(json) {
                if (json.status) {
                    rk.noticeError(json.status);
                    return;
                }
                if (json.data) {
                    if (firstTime) {
                        pmTitle.trigger("loadData", [json.data]);
                    }
                    pmDialogue.trigger("loadData", [json.data, firstTime]);

                    if (scrollFunction) {
                        scrollFunction(pmDialogue);
                    }
                    if (json.data.hasMore && hasMoreFunction) {
                        hasMoreFunction(json.data);
                    }
                }
            }).fail(function(def, code, message) {});
        },
        _parseDate: function(date) {
            var ct = new Date();
            var dateString = '';
            if (date.getFullYear() === ct.getFullYear()) {
                dateString = Globalize.format(date, rk.i18n('PRIVATEMSG_FORMAT_DATE_MONTH_DAY_HOUR_MIN'));
            } else {
                dateString = Globalize.format(date, rk.i18n('PRIVATEMSG_FORMAT_DATE_YEAR_MONTH_DAY_HOUR_MIN'));
            }
            return dateString;
        },
        /**
         * 用于给dialog append最新的数据
         * @param data
         * @param firstTime
         * @param isAppend
         */
        appendData: function(data) {
            var me = this;
            var elem = me.element;
            var pmDialogue = me.pmDialogue;
            pmDialogue.trigger("loadData", [data, false, true]);
            setTimeout(function() {
                elem.find("div.pm-messagebox-body").beScrollTo('bottom');
            }, 50);
        },
        _emoji: function(str) {
            var RE = /(\[(.*?)\])/g;

            var _ALL_EMOJI = {
                replace: function(key) {
                    return this[key] ? '<img src="' + this[key] + '" />' : key;
                }
            };

            $.each('微笑,呲牙,偷笑,发呆,抠鼻,流泪,擦汗,亲亲,坏笑,疑问,色,害羞,委屈,可怜,再见,晕,奋斗,鄙视,睡,衰,握手,抱拳,拳头,勾引,OK,NO,胜利,差劲,强,弱,爱心,心碎,蛋糕,药,菜刀,咖啡,啤酒,示爱,炸弹,便便'.split(','), function(i, name) {
                _ALL_EMOJI['[' + name + ']'] = "/img/em/" + (i + 1) + '.png';
            });

            return str.replace(RE, function($1) {
                return _ALL_EMOJI.replace($1);
            });
        },
        _unescapeEntity: function(s) {
            var REGX_HTML_DECODE = /&\w+;|&#(\d+);/g;

            var HTML_DECODE = {
                "&lt;": "<",
                "&gt;": ">",
                "&amp;": "&",
                "&nbsp;": " ",
                "&#34;": "\"",
                "&copy;": "",
                "&#39;": "'"

                // Add more
            };
            s = (s != undefined) ? s : '';
            return (typeof s != "string") ? s :
                s.replace(REGX_HTML_DECODE,
                    function($0, $1) {
                        var c = HTML_DECODE[$0];
                        if (c == undefined) {
                            // Maybe is Entity Number
                            if (!isNaN($1)) {
                                c = String.fromCharCode(($1 == 160) ? 32 : $1);
                            } else {
                                c = $0;
                            }
                        }
                        return c;
                    });
        }
    });
});